package se.webbzon.oschi01.nbt;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import se.webbzon.oschi01.singleton.Singleton;
import se.webbzon.oschi01.singleton.Singletons;

public class CompoundTagFactory extends AbstractTagFactory<Iterable<Tag<?>>> implements Singleton {

	private CompoundTagFactory() {
		super(Tags.TAG_COMPOUND, "TAG_Compound");
	}

	@Override public CompoundTag readTag(String tagName, DataInputStream is) throws IOException {
		CompoundTag tag = new CompoundTag(this, tagName);
		AbstractNBTReader reader = Singletons.instance(NBTDataInputStreamReader.class);
		while (true) {
			Tag<?> t = reader.read(is);	
			if (t instanceof EndTag)
				break;
			tag.addTag(t);
		}
		return tag;
	}

	@Override public void writeTag(Tag<Iterable<Tag<?>>> tag, DataOutputStream dos) throws IOException {
		Iterable<Tag<?>> children = tag.getValue();
		NBTDataOutputStreamWriter writer = Singletons.instance(NBTDataOutputStreamWriter.class);
		for (Tag<?> child : children) {
			writer.genericWrite(child, dos);
		}
		dos.writeByte(0);
	}

	@Override public Tag<Iterable<Tag<?>>> createTag(String tagName) {
		return new CompoundTag(this, tagName);
	}

}
